package com.geek.gkpush.framework.event.core;

import com.geek.gkpush.framework.dispatch.SpringCtxUtils;
import com.geek.gkpush.framework.event.EventMsgHandler;
import com.geek.gkpush.framework.event.EventMsgPersistFacade;
import com.geek.gkpush.framework.event.action.EventMsgUpdateAction;
import com.geek.gkpush.framework.event.factory.EventMsgContextFactory;
import com.geek.gkpush.framework.event.model.EventMsgContext;
import com.geek.gkpush.framework.event.model.EventMsgDTO;
import com.geek.gkpush.framework.event.model.EventResult;
import com.geek.gkpush.framework.retry.RetryMsgHandler;
import com.geek.gkpush.framework.retry.model.RetryDelayModel;
import com.geek.gkpush.framework.retry.model.RetryResult;
import com.geek.gkpush.framework.threadpool.executor.EagerExecutor;
import com.geek.gkpush.framework.threadpool.runnable.AbstractRunnable;
import com.geek.gkpush.util.excp.ExcpStackUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionException;

/**
 * <h1>事件处理抽象接口的抽象类。</h1><br/>
 *
 * <h1><br/><a href="https://u.geekbang.org/subject/arch3/100614201">Java 业务架构实战营：https://u.geekbang.org/subject/arch3/100614201</a></h1><br/><h1><a href="https://gitee.com/ylimhhmily/BizArchPracticeCamp">Java 业务架构实战营代码地址：https://gitee.com/ylimhhmily/BizArchPracticeCamp</a></h1><br/><h1><a href="https://u.geekbang.org/subject/java4th/1001148?source=app_share">高级 Java 工程体系课 2023 版：https://u.geekbang.org/subject/java4th/1001148?source=app_share</a></h1><br/><h1><a href="https://time.geekbang.org/column/intro/100312101?tab=catalog">Dubbo 源码剖析与实战：https://time.geekbang.org/column/intro/100312101?tab=catalog</a></h1>
 *
 * @author hmilyylimh
 *         ^_^
 * @version 0.0.1
 *         ^_^
 * @date 2023/10/2
 *
 */
@Slf4j
public abstract class AbstractEventMsgHandler implements EventMsgHandler, RetryMsgHandler {

    @Resource(name = "defaultEventMsgExecutor")
    private EagerExecutor eagerExecutor;
    @Autowired
    private EventMsgUpdateAction eventMsgUpdateAction;
    @Autowired
    private EventMsgPersistFacade eventMsgPersistFacade;

    /**
     * <h2>子类必须重写的方法，拿着 MsgContext#msgContent 内容去处理业务逻辑，注意该实现逻辑要能支持可重复执行。</h2><br/><br/>
     *
     * @param msgCtx
     * @return
     */
    public abstract EventResult doProcessEventMsg(EventMsgContext msgCtx);

    @Override
    public void asyncProcessEventMsg(EventMsgContext msgCtx) {
        try {
            getExecutor().execute(new AbstractRunnable() {
                @Override
                public void irun() {
                    asyncProcessEventMsgInner(msgCtx);
                }
            });
        } catch (RejectedExecutionException e) {
            log.error("asyncProcessEventMsg RejectedExecutionException.", e);
        } catch (Exception e) {
            log.error("asyncProcessEventMsg Exception.", e);
        } catch (Throwable e){
            log.error("asyncProcessEventMsg Error.", e);
        }
    }

    private void asyncProcessEventMsgInner(EventMsgContext msgCtx) {
        String simpleName = getClass().getSimpleName();
        try {
            log.info("Begin {}.asyncProcessEventMsgInner.", simpleName);
            EventResult result = doProcessEventMsg(msgCtx);

            if (result.toSuccFlag()) {
                log.info("Succ {}.asyncProcessEventMsgInner.", simpleName);
                eventMsgUpdateAction.update2Succ(msgCtx, null);
                SpringCtxUtils.publishEvent(EventMsgSuccEvent.create(msgCtx));
            } else {
                log.info("Failed {}.asyncProcessEventMsgInner.", simpleName);
                eventMsgUpdateAction.update2Fail(msgCtx, result.toJson());
                SpringCtxUtils.publishEvent(EventMsgFailEvent.create(msgCtx));
            }
        } catch (Exception e) {
            log.error(String.format("Exception %s.asyncProcessEventMsgInner", simpleName), e);
        }
    }

    @Override
    public RetryResult asyncProcessRetryMsg(RetryDelayModel task) {
        String simpleName = getClass().getSimpleName();
        String bizValue = task.getBizValue();
        EventMsgDTO dbEventMsg = eventMsgPersistFacade.queryObjectById(bizValue);

        RetryResult retryResult = null;
        EventMsgContext msgCtx = EventMsgContextFactory.create(dbEventMsg);
        try {
            log.info("Begin {}.asyncProcessRetryMsg.", simpleName);
            EventResult result = doProcessEventMsg(msgCtx);

            if (result.toSuccFlag()) {
                log.info("Succ {}.asyncProcessRetryMsg.", simpleName);
                retryResult = RetryResult.createSucc();
            } else {
                log.info("Failed {}.asyncProcessRetryMsg.", simpleName);
                retryResult = RetryResult.createFail(result.toJson());
            }
        } catch (Exception e) {
            log.error(String.format("Exception %s.asyncProcessRetryMsg", simpleName), e);
            retryResult = RetryResult.createFail(ExcpStackUtils.getStackTrace(e));
        }

        return retryResult;
    }

    @Override
    public Executor getExecutor() {
        return eagerExecutor;
    }
}